<template>
    <div id="terminal" class="terminal-container"></div>
</template>

<script setup>
import { onMounted } from 'vue';

// 定义导出函数、消息
defineExpose({ clearTerminal, addLog, fit });

// 引入terminal相关的第三方库
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import '@xterm/xterm/css/xterm.css';

// terminal panel相关属性
const terminal = new Terminal({
    fontFamily: "'Ubuntu Mono', monospace",
    fontSize: 16,
    fontWeight: 'normal',
    scrollback: 2000
});
const fitAddon = new FitAddon();

// 定义处理函数
function clearTerminal() {
    terminal.write('\x1b[3J\x1b[H\x1b[2J');
}

function addLog(logData) {
    if (logData.length == 0) {
        return;
    }

    // 写入新的数据
    let logs = logData.split('\n');
    let output = '';
    logs.forEach((log) => {
        let logtxt = log.trim();
        if (logtxt.length !== 0) {
            // console.log(log.trim());
            output += log.trim() + '\r\n';
        }
    });
    // console.log(output);
    terminal.write(output);
}

function fit() {
    fitAddon.fit();
}

function initTerminal() {
    // 创建terminal实例并添加FitAddon
    terminal.loadAddon(fitAddon);
    terminal.open(document.getElementById('terminal'));
    fitAddon.fit();
}

onMounted(async () => {
    initTerminal();
});
</script>

<style scoped>
.terminal-container {
    background: #1e1e1e;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.terminal-container :deep(.xterm-viewport) {
    overflow: auto;
}

.terminal-container :deep(.xterm) {
    padding: 5px;
    height: 100%;
}
</style>
